package com.lovo.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.project.enums.UserRoleCodeEnum;
import com.lovo.project.exception.OurException;
import com.lovo.project.service.UserRoleService;
import com.lovo.project.service.impl.UserRoleServiceImpl;
import com.lovo.project.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "RoleUpdateServlet",value = "/updateRole")
public class RoleUpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserRoleService userRoleService = new UserRoleServiceImpl();
        try {
            int userId = Integer.parseInt(request.getParameter("userId"));
            String roleIdAddArray = request.getParameter("roleIdAddArray");
            ObjectMapper mapper = new ObjectMapper();
            List list = mapper.readValue(roleIdAddArray, List.class);
            System.out.println(list.size());
            System.out.println(userId+"=================="+roleIdAddArray);
            if(list.size() != 0){
                userRoleService.deleteAllRoleByUserId(userId);
                userRoleService.addRoleByUserIdAndRoleId(userId,list);
            }else{
                userRoleService.deleteAllRoleByUserId(userId);
            }
            response.getWriter().println(ResultVO.success().toJson());
        } catch (OurException e) {
            response.getWriter().println(ResultVO.fail(e.getCodeEnum()));
        } catch (Exception e) {
            response.getWriter().println(ResultVO.fail(UserRoleCodeEnum.USER_ROLE_UNKNOW_ENUM));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
